<?php
namespace app\api\controller;

use app\common\model\FinancialRecordsModel;
use app\common\service\UserService;
use app\index\model\UserModel;
use think\admin\Controller;
use Omnipay\Omnipay;

/**
 * Class Index
 * @package app\index\controller
 */
class User extends Base
{


    public function __construct(\think\App $app)
    {
        parent::__construct($app);
    }

    // 用户登录
    public function Login(){

        if($this->request->isGet()){
            return $this->fetch('login');
        }
        $username = $this->request->post('username');
        $password = $this->request->post('password');

        $user = UserModel::where('username', $username)->find();
        $data = [];

    
        if (!$user || !password_verify($password, $user->password)) {
            return $this->returnError([], '用户名或密码错误，请检查后重试');
        } else {
            $user->last_logintime = time();
            $user->save();
            $data = UserService::userLoginCache($user);
        }

        if($user['status'] != 1){
            return $this->returnError([], '账户已被禁用，请联系微信：song0229liu');
        }

        return $this->returnSuccess($data);
    }

    // 获取用户余额
    public function getUserBalance(){
        $balance = UserModel::where(['id' => $this->user['id']])->value('balance');
        return $this->returnSuccess(['balance' => $balance]);
    }

    // 获取用户信息
    public function userInfo(){
        if($this->token_login_info){
            $data = [
                'roles' => $this->token_login_info['permissions'],
                'username' => $this->token_login_info['username'],
                'avatar' => "https://i.gtimg.cn/club/item/face/img/2/16022_100.gif",
                'permissions' => ["read:system", "write:system", "delete:system"],
            ];
            return $this->returnSuccess($data);
        }else{
            $this->error('用户登录失效', [], 401);
        }
    }

    // 退出登录
    public function loginout(){
        cache($this->token, null);
        return $this->returnSuccess([]);
    }

    // 检测微信登录扫码状态
    public function wechatLoginCheck(){
        $login_key = input('login_key', '', 'string');
        return $this->returnSuccess(cache($login_key));
    }


    // 获取用户列表数据
    public function getUserList(){
        $this->checkUserLogin();
        $username = input('username', '', 'string');
        $status = input('status', '', 'int');
        $where = [];
        if($username){
            $where[] = ['username', 'like', "%{$username}%"];
        }
        if($status){
            $where[] = ['status', '=', $status];
        }
        $list = UserModel::where($where)->append(['login_time_str','login_time_status'])->field("id,name,username,last_logintime")->order('id', 'desc')->select();
        $total = UserModel::where($where)->count();
        return $this->returnSuccess(['list' => $list, 'total' => $total]);
    }


    public function getUserFinancialList(){

        $this->checkUserLogin();

        $daterange = input('daterange', []);

        $start_time = $daterange[0] ?? '';
        $end_time = $daterange[1] ?? '';

        // 时间未输入，默认为当天的时间
        if(!$start_time && !$end_time){
            $start_time = date('Y-m-d 00:00:00');
            $end_time = date('Y-m-d 23:59:59');
        }
        $where = [];

        // 统计接了多少新单
        $userList = UserModel::alias('u')->where($where)->join('boyi_customer c', sprintf('u.id = c.boyi_uid and `c`.`create_time` BETWEEN %s and %s', strtotime($start_time), strtotime($end_time)), 'left')->field('u.id,u.name,count(c.id) new_customer')->group('u.id,u.name')->order('u.id', 'desc')->select();
        // 统计收了多少款项
        $fincialWhere = [];
        $fincialWhere[] = ['created_at', 'between', [$start_time, $end_time]];

        $financialRecord = FinancialRecordsModel::where($fincialWhere)->group('boyi_uid, transaction_type')->field('boyi_uid, transaction_type,sum(amount) as sum_amount')->select();
        $financialRecordArr = [];
        if($financialRecord){
            foreach ($financialRecord as $item) {
                # code...
                $financialRecordArr[$item['boyi_uid'] . '-' . $item['transaction_type']] = $item['sum_amount'];
            }
        }
        $list = [];
        foreach($userList as $key => $user){
            $user = $user->toArray();
            $user['expense_amount'] = $financialRecordArr[$user['id'] . '-expense'] ?? 0;
            $user['income_amount'] = $financialRecordArr[$user['id'] . '-income'] ?? 0;
            $list[] = $user;
        }
        return $this->returnSuccess(['list' => $list]);
    }

}